let qr = require('qr-image');
module.exports = {
    //api返回成功
    apiSuccess(data = '', msg = 'ok', code = 200) {
        this.status = code;
        this.body = { data, msg };
    },

    //api返回失败
    apiError(data = '', msg = 'fail', code = 400) {
        this.status = code;
        this.body = { data, msg };
    },

    //获取token
    getToken(value) {
        return this.app.jwt.sign(value, this.app.config.jwt.secret);
    },

    //验证token
    checkToken(token) {
        return this.app.jwt.verify(token, this.app.config.jwt.secret);
    },

    //发送或者存到消息队列
    sendAndSaveMessage(to_id, message, msg = 'ok') {
        const { app, service } = this;
        //拿到对方的socket
        // let socket = app.ws.user[to_id];
        let userId = this.authUser.id;
        //验证对方是否在线
        if (app.ws.user && app.ws.user[to_id]) {
            //消息推送
            app.ws.user[to_id].send(JSON.stringify({
                to_id,
                msg,
                data: message
            }));
            //存到历史记录中
            service.cache.setList(`chatlog_${to_id}_${message.chat_type}_${userId}`, message);
        } else {
            service.cache.setList('getmessage_' + to_id, message);
        }
        service.cache.setList(`chatlog_${userId}_${message.chat_type}_${to_id}`, message);
    },

    // 生成唯一id
    genID(length) {
        return Number(Math.random().toString().substr(3, length) + Date.now()).toString(36);
    },

    //生成二维码
    getCode(data) {
        var image = qr.image(data, { size: 10 });
        this.response.type = 'image/png';
        this.body = image;
    },
    randomString(length) {
        const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var result = '';
        for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
        return result;
    },
}